package nanguo.not.cloud.auth;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 *
 *   指定路径验证
 * - id: service2_route
 *         uri: http://127.0.0.1:8082
 *         predicates:
 *         - Path=/s2/**
 *         filters:
 *         - StripPrefix=1 # 去掉路径的 n 个前缀
 *         - Auth=true # 输入过滤器类的名称前缀
 */


public class AuthGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        System.out.println("Welcome to AuthGlobalFilter.");
        ServerHttpRequest request = exchange.getRequest();
        String sign = request.getHeaders().get("sign").get(0);
        String token = "1234";
        if(token.equals(sign)) {
            return chain.filter(exchange);
        }
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    @Override
    public int getOrder() {
        return 0;
    }
}